package servlet;

import model.Commodity;
import util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/adminCommodity.do")
public class AdminCommodityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<Commodity> commodities = new ArrayList<>();
        try {
            Connection conn = DBHelper.getConnection();
            String sql = "SELECT cid,number,price,c_name,photo FROM commodity";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()){
                Commodity commodity = new Commodity(rs.getInt("cid"),
                        rs.getInt("number"),
                        rs.getFloat("price"),
                        rs.getString("c_name"),
                        rs.getString("photo"));
                commodities.add(commodity);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        request.getSession().setAttribute("commodities",commodities);
        request.getRequestDispatcher("AdminCommodity.jsp").forward(request,response);
    }
}
